/*
 * @Author: YuDianyun
 * @Email: 44208156@qq.com
 * @Date: 2020-05-29 09:00:00
 * @Last Modified by: YuDianyun
 * @Last Modified time: 2020-05-29 16:00:00
 * @Description: 图片旋转画图demo
 */
import 'dart:typed_data';       

import 'package:flutter/material.dart';
import 'package:flutter_code_framework/utils/global.dart';
import 'package:flutter_sfsymbols/flutter_sfsymbols.dart';
import 'package:flutter_speed_dial/flutter_speed_dial.dart';
import 'package:painter/painter.dart';
import 'package:flutter/rendering.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
//import 'package:dio/dio.dart';
import 'dart:ui' as ui;
import 'package:extended_image/extended_image.dart';

class ImageDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Painter Example',
      home: new ExamplePage(),
    );
  }
}

class AspectRatioItem {
  AspectRatioItem({this.value, this.text});
  final String text;
  final double value;
}

class ExamplePage extends StatefulWidget {
  @override
  _ExamplePageState createState() => new _ExamplePageState();
}

class _ExamplePageState extends State<ExamplePage> {  
  PainterController _controller;

  GlobalKey _globalKey = GlobalKey();
  final GlobalKey<ExtendedImageEditorState> editorKey =
      GlobalKey<ExtendedImageEditorState>();

  @override
  void initState() {
    super.initState();
    _controller = _newController();

    PermissionHandler().requestPermissions(<PermissionGroup>[
      PermissionGroup.storage, // 在这里添加需要的权限
    ]);
  }

  PainterController _newController() {
    PainterController controller = new PainterController();
    controller.thickness = 5.0;
    controller.backgroundColor = Colors.transparent;
    controller.drawColor = Colors.red;
    return controller;
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> actions;
    actions = <Widget>[
      new IconButton(
          icon: new Icon(
            Icons.undo,
          ),
          tooltip: 'Undo',
          onPressed: () {
            if (_controller.isEmpty) {
              // showModalBottomSheet(
              //     context: context,
              //     builder: (BuildContext context) =>
              //         new Text('Nothing to undo'));
            } else {
              _controller.undo();
            }
          }),
      new IconButton(
          icon: new Icon(Icons.delete),
          tooltip: 'Clear',
          onPressed: _controller.clear),      
      new IconButton(
          icon: new Icon(Icons.rotate_left),
          tooltip: 'Rotate Left',
          onPressed: () => {editorKey.currentState.rotate(right: false)}),
      new IconButton(
          icon: new Icon(Icons.rotate_right),
          tooltip: 'Rotate Right',
          onPressed: () => {editorKey.currentState.rotate(right: true)}),
      // new IconButton(
      //     icon: new Icon(Icons.restore),
      //     tooltip: 'Reset',
      //     onPressed: () => {editorKey.currentState.reset()}),
      new IconButton(
          icon: new Icon(Icons.check),
          onPressed: () =>
              _saveScreen()), //_show(_controller.finish(), context)),
    ];
    return new Scaffold(
      appBar: new AppBar(
        title: const Text('Painter Example'),
        actions: actions,
        // bottom: new PreferredSize(
        //   child: new DrawBar(_controller),
        //   preferredSize: new Size(MediaQuery.of(context).size.width, 30.0),
        // )
      ),
       floatingActionButton: 
      //SpeedDial(
      //     child: Icon(
      //       SFSymbols.pencil_outline,
      //       color: G.ADColor("#EC7364", alpha: 0.9),
      //       size: 38.0,
      //     ),
      //     marginRight: 18, //右边距
      //     marginBottom: 18, //下边距
      //     //animatedIcon: AnimatedIcons.menu_close,//带动画的按钮
      //     //animatedIconTheme: IconThemeData(size: 22.0),
      //     visible: true, //是否显示按钮
      //     closeManually: true, //是否在点击子按钮后关闭展开项
      //     //curve: Curves.bounceIn,//展开动画曲线
      //     overlayColor: Colors.transparent, //遮罩层颜色
      //     overlayOpacity: 0, //遮罩层透明度
      //     onOpen: () => null,//print('OPENING DIAL'), //展开回调
      //     onClose: () => null,//print('DIAL CLOSED'), //关闭回调
      //     tooltip: '编辑', //长按提示文字
      //     heroTag: '', //hero标记
      //     backgroundColor: Colors.blue, //按钮背景色
      //     foregroundColor: Colors.transparent, //按钮前景色/文字色
      //     elevation: 8.0, //阴影
      //     //shape: CircleBorder(),//shape修饰

      //     children: [
      //       SpeedDialChild(
      //         child: Icon(SFSymbols.rotate_right,
      //             color: G.ADColor("#39876E", alpha: 0.98), size: 34),
      //         //backgroundColor: Colors.transparent,
      //         label: '右转90度',
      //         labelStyle: TextStyle(fontSize: 18.0),
      //         onTap: () => {editorKey.currentState.rotate(right: true)},
      //       ),
      //       SpeedDialChild(
      //         child: Icon(SFSymbols.rotate_left,
      //             color: G.ADColor("#39876E", alpha: 0.98), size: 34),
      //         //backgroundColor: Colors.transparent,
      //         label: '左转90度',
      //         labelStyle: TextStyle(fontSize: 18.0),
      //         onTap: () => {editorKey.currentState.rotate(right: false)},
      //       ),
      //       SpeedDialChild(
      //         child: Icon(
      //           SFSymbols.arrowshape_turn_up_left_circle,
      //           color: G.ADColor("#B5B5B5"),
      //           size: 38.0,
      //         ),
      //         //backgroundColor: Colors.red,
      //         label: '撤销',
      //         labelStyle: TextStyle(fontSize: 18.0),
      //         onTap: () => {
      //           if (_controller.isEmpty) {} else {_controller.undo()},
      //         },
      //       ),SpeedDialChild(
      //         child: Icon(Icons.delete),
      //         //backgroundColor: Colors.red,
      //         label: '清除',
      //         labelStyle: TextStyle(fontSize: 18.0),
      //         onTap: () => _controller.clear(),
      //       ),
      //     ]),
      /*body: new Center(
          child: new AspectRatio(
              aspectRatio: 1.0, child: new Painter(_controller))),
      */
      SpeedDial(
              child: Icon(
                SFSymbols.pencil_outline,
                color: G.ADColor("#EC7364", alpha: 0.9),
                size: 38.0,
              ),
              marginRight: 18, //右边距
              marginBottom: 18, //下边距
              //animatedIcon: AnimatedIcons.menu_close,//带动画的按钮
              //animatedIconTheme: IconThemeData(size: 22.0),
              visible: true, //是否显示按钮
              closeManually: true, //是否在点击子按钮后关闭展开项
              //curve: Curves.bounceIn,//展开动画曲线
              overlayColor: Colors.transparent, //遮罩层颜色
              overlayOpacity: 0, //遮罩层透明度
              onOpen: () => null, //print('OPENING DIAL'), //展开回调
              onClose: () => null, //print('DIAL CLOSED'), //关闭回调
              tooltip: '编辑', //长按提示文字
              heroTag: '', //hero标记
              backgroundColor:G.ADColor("#DDDDDD",alpha:0.5),// Colors.blue, //按钮背景色
              foregroundColor: G.ADColor("#DDDDDD",alpha:0.5),//Colors.transparent, //按钮前景色/文字色
              elevation: 8.0, //阴影
              //shape: CircleBorder(),//shape修饰

              children: [
                  SpeedDialChild(
                    child: Icon(Icons.delete,color: G.ADColor("#B5B5B5"),),
                    backgroundColor: G.ADColor("#DDDDDD",alpha:0.5),
                    //foregroundColor: G.ADColor("#B5B5B5"),
                    // label: '清除',
                    // labelStyle: TextStyle(fontSize: 18.0),
                    onTap: () => _controller.clear(),
                  ),
                  SpeedDialChild(
                    child: Icon(
                      SFSymbols.arrowshape_turn_up_left_circle,
                      color: G.ADColor("#B5B5B5"),
                      size: 38.0,
                    ),
                    backgroundColor: G.ADColor("#DDDDDD",alpha:0.5),
                    //foregroundColor: G.ADColor("#B5B5B5"),
                    //backgroundColor: Colors.red,
                    // label: '撤销',
                    // labelStyle: TextStyle(fontSize: 18.0),
                    onTap: () => {
                      if (_controller.isEmpty) {} else {_controller.undo()},
                    },
                  ),
                  SpeedDialChild(
                    child: Icon(SFSymbols.rotate_left,
                        color: G.ADColor("#39876E", alpha: 0.98), size: 34),
                    //backgroundColor: Colors.transparent,
                    // label: '左转90度',
                    // labelStyle: TextStyle(fontSize: 18.0),
                    onTap: () => {editorKey.currentState.rotate(right: false),},
                    backgroundColor: G.ADColor("#DDDDDD",alpha:0.5),
                    //foregroundColor: G.ADColor("#B5B5B5"),
                  ),
                  SpeedDialChild(
                    child: Icon(SFSymbols.rotate_right,
                        color: G.ADColor("#39876E", alpha: 0.98), size: 34),
                    //backgroundColor: Colors.transparent,
                    // label: '右转90度',
                    // labelStyle: TextStyle(fontSize: 18.0),
                    onTap: () => {editorKey.currentState.rotate(right: true)},
                    backgroundColor: G.ADColor("#DDDDDD",alpha:0.5),
                  ),
                ]),
      body: new Center(
        child: new RepaintBoundary(
          key: _globalKey,
          child: new Stack(
            alignment: Alignment.center,
            children: <Widget>[
              Container(
                color: Colors.transparent,
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.height,
                //child: Image.asset('images/girl02.png', fit: BoxFit.contain),
                child: ExtendedImage.asset(
                  //'images/girl03.png',
                  'lib/assets/images/edit/girl03.png',
                  fit: BoxFit.contain,
                  mode: ExtendedImageMode.editor,
                  enableLoadState: true,
                  extendedImageEditorKey: editorKey,
                  initEditorConfigHandler: (ExtendedImageState state) {
                    return EditorConfig(
                        maxScale: 8.0,
                        cropRectPadding: const EdgeInsets.all(0.0),
                        cornerSize: Size(0.0, 0.0),
                        cornerColor: Colors.transparent,
                        lineColor: Colors.transparent,
                        lineHeight: 0.6,
                        editorMaskColorHandler:
                            null, //scaffoldBackgroundColor.withOpacity(pointerDown ? 0.4 : 0.8)
                        hitTestSize: 0.0,
                        cropAspectRatio: null,
                        initCropRectType: InitCropRectType.layoutRect);
                  },
                ),
              ),
              // ExtendedImage.asset(
              //   'images/girl02.png',
              //   fit: BoxFit.cover,
              //   mode: ExtendedImageMode.none,
              //   enableLoadState: true,
              //   extendedImageEditorKey: editorKey,
              //   // initEditorConfigHandler: (ExtendedImageState state) {
              //   //   return EditorConfig(
              //   //       maxScale: 8.0,
              //   //       cropRectPadding: const EdgeInsets.all(0.0),
              //   //       hitTestSize: 0.0,
              //   //       initCropRectType: InitCropRectType.layoutRect,
              //   //       cropAspectRatio: _aspectRatio.value);
              //   // },
              // ),
              // DecoratedBox(
              //   decoration: BoxDecoration(color: Colors.yellow),
              //   child: RotatedBox(
              //     quarterTurns: 1, //旋转180度(2/4圈)
              //     child: Text("Hello world"),
              //   ),
              // ),
              //Image.asset('images/girl03.png', fit: BoxFit.cover),
              // Container(
              //   width: 300.0,
              //   height:400.0,
              //   color: Colors.red,
              // ),
              new Painter(_controller),
            ],
          ),
        ),
      ),
    );
  }

  _saveScreen() async {
    RenderRepaintBoundary boundary =
        _globalKey.currentContext.findRenderObject();

    ui.Image image = await boundary.toImage();
    ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    final result =
        await ImageGallerySaver.saveImage(byteData.buffer.asUint8List());
    print(result);
  }
}